<template>
  <div class="tui-switch">
    <span :title="text" class="label-list-info" v-show="text">{{text}}</span>
    <input type="checkbox" ref='switch' @click="handleClick" @change="handlechange" />
    <label :style="{'width':width+'px','height':height+'px'}">
      <!-- 小球 -->
      <span class="span" :style="{'width':height+'px','left':spanLeft+'px'}"></span>
    </label>
  </div>
</template>
<script>
export default {
  name: "TuiSwitch",
  componentName: "TuiSwitch",
  data() {
    return {
      // 小球水平移动距离
      spanLeft: 0
    };
  },
  // 实现父子组件的v-model
  model: {
    prop: "checked",
    event: "change"
  },
  props: {
    present:[Object,String],
    text: String,
    value: {
      type: [String, Boolean],
      default: false
    },
    width: {
      type: [String, Number],
      default: 60
    },
    height: {
      type: [String, Number],
      default: 20
    },
    activeColor: {
      type: String,
      default: "#3399ff"
    },
    inActiveColor: {
      type: String,
      default: "#ffffff"
    }
  },
  computed: {
    // 对传入的字符串进行转换
    valueComputed() {
      if (typeof this.value === "string") {
        return this.value === "0" ? false : true;
      } else if (typeof this.value === "boolean") {
        return this.value;
      } else {
        return false;
      }
    }
  },
  methods: {
    handleClick(e) {
      // 解决小球水平移动距离的动态设置问题
      if (e.target.checked) {
        this.spanLeft = this.width - this.height;
      } else {
        this.spanLeft = 0;
      }
    },
    handlechange(event){
      if(this.present){
        this.$emit('change', event.target.checked, this.present);
      }else {
        this.$emit('change', event.target.checked);
      }
       
    }
  },
  mounted() {
    var bool = this.valueComputed;
    this.$refs.switch.checked = bool;
    if (bool) {
      this.spanLeft = this.width - this.height;
    } else {
      this.spanLeft = 0;
    }
  }
};
</script>

<style>
.tui-switch {
  position: relative;
  display: inline-block;
}
.tui-switch label {
  background: #ccc;
  position: relative;
  display: inline-block;
  border-radius: 46px;
  -webkit-transition: 0.4s;
  transition: 0.4s;
}
.tui-switch .span {
  display: block;
  position: absolute;
  height: inherit;
  border-radius: 100%;
  left: 0;
  top: 0px;
  z-index: 2;
  background: #fff;
  -webkit-transition: 0.4s;
  transition: 0.4s;
}
.tui-switch input {
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
  opacity: 0;
  cursor: pointer;
}
.tui-switch input:checked + label {
  background: #2980b9;
}
.tui-switch input:checked + label > span {
  background: rgba(48, 100, 215, 0.6);
}
</style>
// tang 18/8/16 更新日志
// 1.增加：组件动态设置宽高的功能
// 2.增加：小球跟随组件宽高自动改变大小和移动距离
// 3.修改：小球不使用伪元素，改用span，利于动态改变样式

// tang 18/8/18 更新日志
//1.增加：原始v-model功能没有改变基础上，支持将:value传入的props为0/1的情况下转换为布尔值，父组件通过change时间更新数据

